import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import router from '@/router/index'
let loadingInstance

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: '/api/',
  // withCredentials: false, // send cookies when cross-domain requests 默认false
  headers: {
    // 'Content-Type': 'application/json; charset=utf-8'
  },
  timeout: 50000, // request timeout
  // paramsSerializer: function(params) {
  //   return qs.stringify(params, { arrayFormat: 'brackets' })
  // }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    loadingInstance = Loading.service({
      fullscreen: true,
      lock: true,
      text: '加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    if (store.getters.token) {
      // let each request carry token
      // ['jwt-token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    loadingInstance.close()
    const res = response.data
    if (res.code !== 200) {
      if (res.code !== 420) {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 3 * 1000,
          showClose: true
        })
      }
      // 401: 登录失效 / 登录失败
      if (res.code === 401) {
        // to re-login
        store.dispatch('user/resetToken').then(() => {
          setTimeout(() => {
            if (router.history.current.path !== '/login') {
              location.reload()
            }
          }, 1500)
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    loadingInstance.close()
    Message({
      dangerouslyUseHTMLString: true,
      message: `<p> ${error.message}</p>`,
      type: 'error',
      duration: 5 * 1000,
      showClose: true
    })
    return Promise.reject(error)
  }
)

export default service
